/**
 * created by 小卷毛, 2021-06-12
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl.viewmodel

import android.content.Context
import com.amap.api.AMapLocationHelper
import com.amap.api.LatLngHelper
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.okrx.adapter.SingleBody
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.convert.StringConvert
import com.lzy.okgo.utils.OkLogger
import com.rzico.sbl.R
import com.rzico.sbl.model.BaseUrl
import com.tim.library.doForeground
import com.xinnuo.common.extend.condition
import com.xinnuo.common.helper.AppSettingHelper.goAutoStartSetting
import com.xinnuo.common.helper.getInt
import com.xinnuo.common.helper.isCodeTel
import com.xinnuo.common.manager.LocationManager
import com.xinnuo.common_ui.utils.applySchedulers
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess

/**
 * 描 述：首页面操作相关
 * 作 者：小卷毛  2021-06-12 11:15
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class MainViewModel : UpdateViewModel() {

    /**
     * 设置腾讯云在线推送
     */
    fun setIMPushOnline() {
        doForeground {
            onSuccess { OkLogger.i("在线推送成功") }
            onError { _, desc ->
                OkLogger.e("在线推送失败：$desc")
            }
        }
    }

    /**
     * 后台运行提示框
     */
    fun showBatteryDialog(context: Context) {
        context.apply {
            (getInt("startCount") == 0)
                .condition {
                    showHintDialog(
                        title = "后台运行",
                        hint = "为避免应用在后台运行中出现推送异常、误杀等问题，建议您为${getString(R.string.app_name)}开启后台运行权限。",
                        sure = "去设置",
                        onSure = { goAutoStartSetting() }
                    )
                }
        }
    }

    /**
     * 定位初始化
     */
    fun initLocation(context: Context) {
        AMapLocationHelper
            .getInstance(context)
            .setDuration(5000)
            .addCallback(200) { location, isSucceed ->
                isSucceed.condition {
                    uploadLocation(
                        location.latitude,
                        location.longitude
                    )
                }
            }
    }

    /**
     * GPS定位监听
     */
    fun initGpsListener() {
        LocationManager
            .instance
            .listenScope(
                hashKey = 200,
                duration = 5000,
                callback = {
                    val latLng =
                        LatLngHelper.gps84ToGcj02(
                            it.latitude,
                            it.longitude
                        )

                    uploadLocation(latLng[0], latLng[1])
                }
            )
    }

    /**
     * 上报实时位置，无缓存和重复机制
     */
    private fun uploadLocation(lat: Double, lng: Double) {
        OkGo.getInstance()
            .cancelTag(BaseUrl.latLng)

        OkGo.post<String>(BaseUrl.latLng)
            .tag(BaseUrl.latLng)
            .cacheMode(CacheMode.NO_CACHE)
            .retryCount(0)
            .params("lat", lat)
            .params("lng", lng)
            .converter(StringConvert())
            .adapt(SingleBody())
            .compose(applySchedulers())
            .subscribeBySuccess()
    }

    /**
     * 清除实时位置
     */
    fun clearLocation() {
        request(
            isLoadingBefore = false,
            isLoadingAfter = false,
            isFailed = false,
            requestUrl = BaseUrl.clear
        )
    }

    /**
     * 来电信息上报
     */
    fun reportPhone(number: String) {
        var callNumber = number

        number.isCodeTel()
            .condition {
                callNumber = when {
                    number.startsWith("01") -> number.substring(3)

                    number.startsWith("02") -> number.substring(3)

                    number.startsWith("03") -> number.substring(4)

                    number.startsWith("04") -> number.substring(4)

                    number.startsWith("05") -> number.substring(4)

                    number.startsWith("06") -> number.substring(4)

                    number.startsWith("07") -> number.substring(4)

                    number.startsWith("08") -> number.substring(4)

                    number.startsWith("09") -> number.substring(4)

                    number.startsWith("008") -> number.substring(5)

                    else -> number
                }
            }

        OkGo.post<String>(BaseUrl.manuCallSav)
            .cacheMode(CacheMode.NO_CACHE)
            .retryCount(0)
            .params("mobile", callNumber)
            .converter(StringConvert())
            .adapt(SingleBody())
            .compose(applySchedulers())
            .subscribeBySuccess(
                onSuccess = {
                    LiveEventBus
                        .get("phone_report")
                        .post("refresh")
                }
            )
    }

}